package com.huluobo.a2202kotlindouyindemo.cart

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2202kotlindouyindemo.R
import com.huluobo.a2202kotlindouyindemo.adapter.CartAdapter
import com.huluobo.a2202kotlindouyindemo.databinding.ActivityCartBinding
import com.huluobo.a2202kotlindouyindemo.pay.TotalPayActivity
import com.huluobo.base.bean.CartBean
import com.huluobo.base.view.BaseMVVMActivity

class CartActivity : BaseMVVMActivity<ActivityCartBinding>() {
    private lateinit var viewModel: CartViewModel
    private lateinit var cartAdapter: CartAdapter
    private val cartList = mutableListOf<CartBean>()
    private var totalPrice = 0
    override fun initData() {
        viewModel = ViewModelProvider(this)[CartViewModel::class.java]
        viewModel.getCartList()

        viewModel.getCartListSuccess.observe(this) {
            if (it.code == 200) {
                cartList.clear()
                cartList.addAll(it.data)
                cartAdapter.notifyDataSetChanged()

                it.data.forEach { item ->
                    totalPrice += item.count * item.goods_default_price
                }
                dataBinding.cartTotalPrice.text = "总价:${totalPrice}元"

            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getCartListFailed.observe(this) {
            Log.i("TagA", "购物车获取失败:$it")
        }

    }

    override fun initView() {
        dataBinding.cartRv.layoutManager = LinearLayoutManager(this)
        cartAdapter = CartAdapter(cartList)
        dataBinding.cartRv.adapter = cartAdapter

        dataBinding.cartPay.setOnClickListener {
            val intent = Intent(this, TotalPayActivity::class.java)
            intent.putExtra("totalPrice", totalPrice)
            startActivity(intent)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_cart
}